<template>
	<view class="page">
		<button v-if="!loginStatus" @click="getProfile()" size="mini">
			微信授权登录</button>
		<block v-else>
			<view class="current-user">
				<image 
				@click="updateProfile()"
				class="avatar" 
				:src="userInfo.avatarUrl" mode="scaleToFill"></image>
			</view>
			<view class="">
				{{userInfo.nickName}}
				<view class="">
					{{userInfo.country}}
				</view>
			</view>
			<view 
			@click="goList"
			>
				进入记录
			</view>
		</block>
	</view>
</template>

<script>
	import searchInput from '../../components/search-input/index.vue'
	const context = wx.createInnerAudioContext();
	export default {
		data() {
			return {
				msg: '',
				todoList: [

				],
				list: {
					tempFileURL: ''
				},
				_openid: '',
				count: 0,
			}
		},
		computed: {
			loginStatus() {
				return this.$store.state.global.isLogin
			},
			userInfo() {
				return this.$store.state.global.userinfo
			},
		},
		components: {
			searchInput
		},
		onLoad() {
			wx.cloud.callFunction({
				name: 'login',
				data: {},
				success: res => {
					console.log('[云函数] [login] user openid: ', res.result.openid);
					this._openid = res.result.openid;
					this.onLogin();
				},
				fail: err => {
					console.error('[云函数] [login] 调用失败', err)
				}
			})
		},
		methods: {
			goList() {
				uni.navigateTo({
					url:'../list/index' 
				})
			},
			updateProfile() {
				wx.getUserProfile({
					desc: '更新用户信息',
					success: res => {
						const db = wx.cloud.database();
						db.collection('users').doc(this.userInfo._id).update({
							data: {
								...res.userInfo
							},
							success: () => {
								this.$store.commit('global/setUserinfo', res.userInfo)
							}
						})
					}
				})
			},
			getProfile() {
				wx.getUserProfile({
					desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: (res) => {
						// console.log(res.userInfo)
						this.onRegeister(res.userInfo)
					},
					fail: err => {
						console.log('用户信息获取失败！', err)
					}
				})
			},
			// 登录
			onLogin() {
				const _openid = this._openid
				const db = wx.cloud.database();
				db.collection('users').where({
					_openid
				}).get({
					success: res => {
						if (res.data.length != 0) {
							wx.showToast({
								title: '登录成功！',
							})
							this.$store.commit('global/setUserinfo', res.data[0])
							this.$store.commit('global/setLoginStatus', true)
							// uni.navigateTo({
							// 	url: '../list/index'
							// })
						}
					},
				})
			},
			// 注册
			onRegeister(userinfo) {
				const db = wx.cloud.database();
				db.collection('users').add({
					data: {
						...userinfo,
					},
					success: (res) => {
						this.$store.commit('global/setUserinfo', res.data)
						this.$store.commit('global/setLoginStatus', true)
						wx.showToast({
							title: '注册成功！',
						})
					},
					fail: err => {
						wx.showToast({
							icon: 'none',
							title: '注册失败!'
						})
					}
				})
			},
			onAdd: function() {
				const db = wx.cloud.database()
				db.collection('counters').add({
					data: {
						count: 1
					},
					success: res => {
						// 在返回结果中会包含新创建的记录的 _id
						this.setData({
							counterId: res._id,
							count: 1
						})
						wx.showToast({
							title: '新增记录成功',
						})
						console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
					},
					fail: err => {
						wx.showToast({
							icon: 'none',
							title: '新增记录失败'
						})
						console.error('[数据库] [新增记录] 失败：', err)
					}
				})
			},
			onQuery: function() {
				const db = wx.cloud.database()
				// // 查询当前用户所有的 counters
				db.collection('counters').where({
					_openid: this._openid
				}).get({
					success: res => {
						this.counterId = res.data[0]._id
						this.count = res.data[0].count
						console.log('[数据库] [查询记录] 成功: ', res)
					},
					fail: err => {
						wx.showToast({
							icon: 'none',
							title: '查询记录失败'
						})
						console.error('[数据库] [查询记录] 失败：', err)
					}
				})
			},
			onCounterInc: function() {
				const db = wx.cloud.database()
				const newCount = this.count + 1
				db.collection('counters').doc(this.counterId).update({
					data: {
						count: newCount
					},
					success: res => {
						this.count = newCount
					},
					fail: err => {
						icon: 'none',
						console.error('[数据库] [更新记录] 失败：', err)
					}
				})
			},

			onCounterDec: function() {
				const db = wx.cloud.database()
				const newCount = this.count - 1
				db.collection('counters').doc(this.counterId).update({
					data: {
						count: newCount
					},
					success: res => {
						this.count = newCount
					},
					fail: err => {
						icon: 'none',
						console.error('[数据库] [更新记录] 失败：', err)
					}
				})
			},

			onRemove: function() {
				if (this.data.counterId) {
					const db = wx.cloud.database()
					db.collection('counters').doc(this.data.counterId).remove({
						success: res => {
							wx.showToast({
								title: '删除成功',
							})
							this.setData({
								counterId: '',
								count: null,
							})
						},
						fail: err => {
							wx.showToast({
								icon: 'none',
								title: '删除失败',
							})
							console.error('[数据库] [删除记录] 失败：', err)
						}
					})
				} else {
					wx.showToast({
						title: '无记录可删，请见创建一个记录',
					})
				}
			},
		}
	}
</script>

<style scoped lang="less">
	.page {
		padding: 100rpx 30rpx 30rpx;
		height: 100vh;
		box-sizing: border-box;
		background-color: #000;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-evenly;
		color: #fff;
	}

	.current-user {
		padding: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.avatar {
			width: 180rpx;
			height: 180rpx;
			border-radius: 90rpx;
		}

		text {
			color: #fff;
		}
	}
	.current-count {
		font-size: 90rpx;
		font-weight: 600;
		color: #fff;
	}
</style>
